package com.common.help.test16;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class NIOServer {

	private ServerSocketChannel server;
	private int port;
	private Selector selector;
	private ByteBuffer dst = ByteBuffer.allocate(1024);
	private ByteBuffer src = ByteBuffer.allocate(1024);
	private Map<SelectionKey,String> map = new HashMap<>();
	public NIOServer(int port) throws IOException{
		this.port = port;
		server = ServerSocketChannel.open();
		server.configureBlocking(false);
		server.socket().bind(new InetSocketAddress(port));
		selector = Selector.open();
		server.register(selector, SelectionKey.OP_ACCEPT);
		System.out.println("服务端初始化成功 端口:"+this.port);
	}
	
	public static void main(String[] args) throws IOException {
		new NIOServer(8080).listener();
	}

	private void listener() throws IOException {
		while(true){
			int count = selector.select();
			if(count==0){
				continue;
			}
			Set<SelectionKey> keys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = keys.iterator();
			while(iterator.hasNext()){
				SelectionKey key = iterator.next();
				//进行处理这个从客户端发来的请求
				process(key);
				iterator.remove();
			}
		}
	}

	private void process(SelectionKey key) throws IOException {
		if(key.isAcceptable()){
			SocketChannel client = server.accept();
			client.configureBlocking(false);
			client.register(selector, SelectionKey.OP_READ);
		}else if(key.isReadable()){
			dst.clear();
			SocketChannel client = (SocketChannel)key.channel();
			int len = client.read(dst);
			dst.flip();
			if(len>0){
				String msg = new String(dst.array(),0,len);
				map.put(key, msg);
				System.out.println("收到客户端信息 :"+msg);
			}
			client.register(selector, SelectionKey.OP_WRITE);
		}else if(key.isWritable()){
			src.clear();
			if(!map.containsKey(key)){
				return;
			}
			SocketChannel client = (SocketChannel)key.channel();
			src.put((map.get(key)+":你好 我们收到你的信息！").getBytes());
			src.flip();
			client.write(src);
			client.register(selector, SelectionKey.OP_READ);
		}
		}
}
